package com.cn.jx.manager.service.query.Impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.Query;

import com.cn.jx.common.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cn.jx.common.util.page.PageObj;
import com.cn.jx.manager.dao.MessageUserRepository;
import com.cn.jx.manager.po.Message;
import com.cn.jx.manager.po.MessageUser;
import com.cn.jx.manager.service.query.IMessageServiceQry;

import com.jx.enumType.MessageTypeEnum;
import com.jx.jpaQuery.PageCondition;
import com.jx.util.DateUtil;
import com.jx.util.MapObject;

/**
 * 
 * @author 姜旭
 * @version v1.11.20.2019
 * @since 
 * <p>创建时间：2019年12月23日
 * <p>功能描述：
 * <p>官方网站：management/admin/index
 * <p>邮箱地址：524577360@qq.com
 */
@Service("messageServiceQry") 
@Transactional
public class MessageServiceImplQry  extends BaseService implements IMessageServiceQry {

	@Autowired
	private MessageUserRepository messageUserDao;

	@Override
	@Transactional(readOnly = true)
	public PageObj<MapObject> findEmailMessage(PageCondition page,String uid) throws Exception {
		
		String sql="select m.sender,n.title,m.sendTime,n.type,m.receivStatus,m.id"
				+ " from MessageUser m inner join Message n on n.id=m.messageId";
		
		String sqlCount=" select count(1) from MessageUser m ";
		
		String pam=page.getParam();
		String where=" where ";
		switch (pam) {
		case "0":
			//收件箱 接收 已读和未读
			where=where+" m.delFlg=0 and m.receivMethod='receive' ";
			break;
		case "01":
			//收件箱 接收 已读
			where=where+" m.delFlg=0 and m.receivMethod='receive' and m.receivStatus =1  ";
			break;
		case "00":
			//收件箱 接收 未读
			where=where+" m.delFlg=0 and m.receivMethod='receive' and m.receivStatus =0  ";
			break;
		case "1":
			//已发送 发送 1 已发送
			where=where+" m.delFlg=0 and m.receivMethod='send' and m.receivStatus =1  ";
			break;
		case "2":
			//草稿箱未 发送 0 未发送
			where=where+" m.delFlg=0 and m.receivMethod='send' and m.receivStatus =0  ";
			break;
		case "3":
			//已删除
			where=where+" m.delFlg=1  ";
			break;
		default:
			break;
		}
		where=where+" and m.userId='"+uid+"'";
		String order=" order by m.sendTime desc ";
		
		// 查询并设置参数
		Query query = entityManager.createQuery(sql+where+order);
		Query countQuery = entityManager.createQuery(sqlCount+where);

		Long totalCount = (Long) countQuery.getSingleResult();

		Pageable pageable = PageRequest.of(page.getPage() - 1, page.getRows());
		query.setFirstResult((int) pageable.getOffset());
		query.setMaxResults(pageable.getPageSize());

		@SuppressWarnings("unchecked")
		List<Object[]> puser = query.getResultList();
		List<MapObject> content=new ArrayList<MapObject>();
		for(Object[] m : puser) {
			MapObject mo=MapObject.getInstance();
			mo.put("id", m[5]);
			mo.put("sender", m[0]);
			mo.put("title", m[1]);
			mo.put("sendTime", m[2]);
			mo.put("type", MessageTypeEnum.getName(m[3].toString()));
			mo.put("mailStatus", m[4]);
			mo.put("date", DateUtil.getSpechDateFmt((Date)m[2]));
			mo.put("attach", "");
			content.add(mo);
		}
		//select m.sender,n.title,n.sendTime,n.type
		//[总经理办公室, 职务分派, 2019-12-28 19:49:03.0, 1002]
		Page<MapObject> pagemap = new PageImpl<MapObject>(content, pageable, totalCount);
		PageObj<MapObject> pageJob = PageObj.of(pagemap, content);		
		return pageJob;
	}

	@Override
	@Transactional(readOnly = true)
	public List<MapObject> findLatelyReceiveMessage(String sessionUserId) {
		String sql=" from MessageUser where userId=:userId and receivMethod=:receive and delFlg=0 and sendTime between :stime and :etime "
				+ " order by receivStatus ASC , sendTime DESC ";
		Query query = entityManager.createQuery(sql, MessageUser.class);
		query.setFirstResult(0);
		query.setMaxResults(5);
		query.setParameter("userId", sessionUserId);
		query.setParameter("receive", "receive");
		query.setParameter("stime", DateUtil.getTodayStart());
		query.setParameter("etime", DateUtil.getTodayEnd());
		
		@SuppressWarnings("unchecked")
		List<MessageUser> puser = query.getResultList();
		List<MapObject> content=new ArrayList<MapObject>();
		for(MessageUser mu:puser){
			Message msg=findEntityByPkid(mu.getMessageId(),Message.class);
			MapObject mo=MapObject.getInstance();
			mo.put("sender", mu.getSender());
			mo.put("title",msg.getTitle());
			mo.put("sendTime", mu.getSendTime());
			mo.put("type", MessageTypeEnum.getName(msg.getType()));
			mo.put("mailStatus", mu.getReceivStatus());
			mo.put("date", DateUtil.getSpechDateFmt(mu.getSendTime()));
			mo.put("attach", "");
			content.add(mo);
		}
		return content;
	}
	
	@Override
	@Transactional(readOnly = true)
	public Long findInboxTodayCount(String userId) {
		String sql=" select count(1) from MessageUser where userId=:userId and receivMethod=:receive and delFlg=0 and sendTime between :stime and :etime ";
		Query query = entityManager.createQuery(sql);
		query.setParameter("userId", userId);
		query.setParameter("receive", "receive");
		query.setParameter("stime", DateUtil.getTodayStart());
		query.setParameter("etime", DateUtil.getTodayEnd());
		Long totalCount = (Long) query.getSingleResult();
		return totalCount;
	}

	@Override
	@Transactional(readOnly = true)
	public MapObject findMessage(String mesId) {
		MessageUser muser=findEntityByPkid(mesId,MessageUser.class);
		if(muser!=null){
			Message msg=findEntityByPkid(muser.getMessageId(),Message.class);
			
			MapObject mo=MapObject.getInstance();
			mo.put("sender", muser.getSender());
			mo.put("title",msg.getTitle());
			mo.put("sendTime", muser.getSendTime());
			mo.put("type", MessageTypeEnum.getName(msg.getType()));
			mo.put("mailStatus", muser.getReceivStatus());
			mo.put("content",msg.getContent());
			mo.put("attach", "");
			return mo;
		}
		return null;
	}

	@Override
	@Transactional(readOnly = true)
	public int findInboxTotalCount(String userId) {
		return messageUserDao.findAllInboxCount(userId);
	}

	@Override
	@Transactional(readOnly = true)
	public int findInboxNoReadCount(String userId) {
		return messageUserDao.findAllInboxUnReadCount(userId);
	}

	@Override
	@Transactional(readOnly = true)
	public int findOutboxSendCount(String userId) {
		return messageUserDao.findAllOutboxSendCount(userId);
	}

	@Override
	@Transactional(readOnly = true)
	public int findDeleteCount(String userId) {
		return messageUserDao.findAllDeleteCount(userId);
	}

	@Override
	@Transactional(readOnly = true)
	public int findOutboxUnSendCount(String userId) {
		return messageUserDao.findAllOutboxUnSendCount(userId);
	}

	
}
